﻿@model int
@inject IPictureService pictureService
@inject MediaSettings mediaSettings

@using Nop.Core.Domain.Media
@using Nop.Services.Media

@{
    //other variables
    var random = CommonHelper.GenerateRandomInteger();
    var clientId = "picture" + random;
    var picture = await pictureService.GetPictureByIdAsync(Model);

    const int pictureSize = 100;
}

<noscript>
    <p>Please enable JavaScript to use file uploader.</p>
</noscript>
<input type="hidden" asp-for="@Model" />

<div id="@(clientId)element" class="filepond"></div>

<div class="upload-picture-block">
    <div class="picture-container">
        <div class="uploaded-image">
            <img id="@(clientId + "image")" src="@(await pictureService.GetPictureUrlAsync(Model, pictureSize, true))" width="@(pictureSize)" />
        </div>
    </div>
</div>

@* register CSS and JS *@
<link rel="stylesheet" href="~/lib_npm/filepond/filepond.min.css" />
<link rel="stylesheet" href="~/lib_npm/filepond-plugin-get-file/filepond-plugin-get-file.min.css" />
<script asp-exclude-from-bundle="true" src="~/lib_npm/filepond/filepond.min.js" asp-location="Footer"></script>
<script asp-exclude-from-bundle="true" src="~/lib_npm/filepond-plugin-file-validate-type/filepond-plugin-file-validate-type.min.js" asp-location="Footer"></script>
<script asp-exclude-from-bundle="true" src="~/lib_npm/filepond-plugin-get-file/filepond-plugin-get-file.min.js" asp-location="Footer"></script>


<script asp-location="Footer">
    $(function () {
        // Register the plugins
        FilePond.registerPlugin(FilePondPluginFileValidateType);
        FilePond.registerPlugin(FilePondPluginGetFile);

        var allowedExtensions = ["image/bmp", "image/gif", "image/jpeg", "image/jpg", "image/jpe", "image/jfif", "image/pjpeg", "image/pjp", "image/png", "image/tiff", "image/tif", "image/webp"];
        
        @{
            if (mediaSettings.AllowSVGUploads)
            {
                <text>
                    allowedExtensions.push("image/svg+xml");
                </text>
            }
        }

        // Create a FilePond instance
        const @(clientId)pond = FilePond.create(document.querySelector('#@(clientId)element'), {
            credits: false,
            acceptedFileTypes: allowedExtensions,
            allowMultiple: false,
            maxFiles: 1,
            allowDownloadByUrl: true,
            @if (picture != null)
            {
            <text>
                files: [
                {
                    source: '@Html.Raw($"{picture.SeoFilename}{await pictureService.GetFileExtensionFromMimeTypeAsync(picture.MimeType)}")',
                    options: {
                        type: 'local',
                        metadata: {
                            url: '@(await pictureService.GetPictureUrlAsync(Model, showDefaultPicture: false))' 
                        }
                    }
                },
            ],
            </text>
            }
            server: {
                process:  (fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
                    const formData = new FormData();
                    formData.append(fieldName, file, file.name);

                    const request = new XMLHttpRequest();
                    request.open('POST', '@(Url.Content("~/Admin/Picture/AsyncUpload"))');

                    request.upload.onprogress = (e) => {
                        progress(e.lengthComputable, e.loaded, e.total);
                    };

                    request.onload = function () {
                        const commonError = '@T("Common.Error")';
                        if (request.status < 200 || request.status >= 300) {
                            error(commonError);
                            return;
                        }

                        var r = JSON.parse(request.responseText);
                        if (!r.success) {
                            error(r.message || commonError);
                            return;
                        }

                        load(request.responseText);

                        if (r.success) {
                            $("#@(clientId + "image")").attr("src", r.imageUrl);
                            $("#@(Html.IdForModel())").val(r.pictureId);
                        }
                    };

                    request.send(formData);
                },
                remove: (source, load, error) => {                                      
                    $("#@(Html.IdForModel())").val('0');
                    $("#@(clientId + "image")").attr("src","@await pictureService.GetDefaultPictureUrlAsync(pictureSize)");
                    load();
                },
                revert: (uniqueFileId, load, error) => {
                    $("#@(Html.IdForModel())").val('0');
                    $("#@(clientId + "image")").attr("src","@await pictureService.GetDefaultPictureUrlAsync(pictureSize)");
                    load();
                },
            },
            labelIdle: '@T("Common.FileUploader.DropFiles") / <span class="filepond--label-action">@T("Common.FileUploader.Browse")</span>',
            labelFileProcessing: '@T("Common.FileUploader.Processing")',
            labelFileProcessingError: (err) => err.body
        });


        $("#@(clientId + "remove")").click(function(e) {
            $("#@(clientId + "image")").html("<img src='@await pictureService.GetDefaultPictureUrlAsync(pictureSize)' width='@(pictureSize)' />");
            $("#@(Html.IdForModel())").val(0);
            @(clientId)pond.removeFiles();
            $(this).hide();
        });
    });
</script>